package com.ky.manage.fragment;

import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.ky.manage.BaseApplication;
import com.ky.manage.R;
import com.ky.manage.activity.aftersales.CreateMaintainOrderActivity;
import com.ky.manage.activity.indoor.IndoorMendListDetailActivity;
import com.ky.manage.activity.indoor.IndoorMendListEditDetailActivity;
import com.ky.manage.activity.outdoor.OutdoorSecurityCheckActivity;
import com.ky.manage.adapter.FragmentTabAdapter;
import com.ky.manage.adapter.HomeAdapter;
import com.ky.manage.base.BaseActivity;
import com.ky.manage.base.BaseFragment;
import com.ky.manage.constant.OverallData;
import com.ky.manage.model.LoginUserInfo;
import com.ky.manage.model.response.IndoorMendListResp;
import com.ky.manage.ui.RecycleViewDivider;
import com.ky.manage.utils.ImageLoader.GlideImageLoader;
import com.ky.manage.utils.ScreenUtils;
import com.ky.manage.utils.Utils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

/**
 * 首页TAB页
 * 户内修改记录
 */
public class HomeFragment extends BaseFragment {
    private HomeAdapter mHomeAdapter;
    private int mCurPageIndex = OverallData.DEFAULT_REQ_PAGE_NUM;
    private int mCurListCnt;
    //private RefreshLayout refreshLayout;
    private ImageView mToTopIv;
    private RecyclerView recyclerView;
    private boolean mIsReqListData = false;
    /**
     * 状态（0正常， 1待整改， 2已整改）
     */
    private String mStatus;


    private ViewPager mPager;
    private RadioGroup mTabRg;
    private List<Fragment> mFragmentList = new ArrayList<>();

    private ProductFragment productFragment;
    private MountingsFragment mountingsFragment;
    private SCLogFragment scLogFragment;

    public HomeFragment() {
    }

    /**
     * 状态（0正常， 1待整改， 2已整改）
     * "":全部
     * 1：待整改
     * 2：2已整改
     */
    public HomeFragment(String status) {
        this.mStatus = status;
    }

    @Override
    protected int layoutId() {
        return R.layout.layout_home_tab_fragment;
    }

    @Override
    protected void initView(View rootView) {
        mToTopIv = findView(R.id.to_top_iv, v -> {
            //置顶
            recyclerView.smoothScrollToPosition(0);
            mToTopIv.setVisibility(View.GONE);
        });
        recyclerView = findView(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.VERTICAL,
                ScreenUtils.dp2px(10), mContext.getColor(R.color.gray_light)));
        mHomeAdapter = new HomeAdapter(mContext, R.layout.layout_zheng_gai_log_item, new ArrayList<>());
        initHeadView();
        mHomeAdapter.setOnItemClickListener((adapter , view , position) -> {
            //条目点击
            IndoorMendListResp.IndoorMendInfo indoorMendInfo = mHomeAdapter.getItem(position);
            if ("1".equals(indoorMendInfo.status)) {
                //待整改
                IndoorMendListEditDetailActivity.toIndoorMendEditDetailPage((BaseActivity) getActivity(),
                        indoorMendInfo.recordId, indoorMendInfo.indoorId);
            } else {
                //已整改
                IndoorMendListDetailActivity.toIndoorMendListDetailPage((BaseActivity)getActivity(),
                        indoorMendInfo.recordId, indoorMendInfo.indoorId);
            }
        });
        recyclerView.setAdapter(mHomeAdapter);
        mHomeAdapter.notifyDataSetChanged();

        /*refreshLayout = findView(R.id.refreshLayout);
        refreshLayout.setRefreshHeader(new ClassicsHeader(mContext));
        refreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
        refreshLayout.autoRefresh();
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            if (mIsReqListData) {
                return;
            }
            mCurPageIndex = OverallData.DEFAULT_REQ_PAGE_NUM;
            requestIndoorMendListData();
        });
        refreshLayout.setOnLoadMoreListener(refreshlayout -> {
            if (mIsReqListData) {
                return;
            }
            mToTopIv.setVisibility(mCurPageIndex > 2 ? View.VISIBLE : View.GONE);
            requestIndoorMendListData();
        });*/

    }

    /**
     * 无数据界面
     */
    /*private void showEmptyView() {
        mHomeAdapter.getData().clear();
        mHomeAdapter.setEmptyView(R.layout.layout_empty_data);
        mHomeAdapter.notifyDataSetChanged();
    }*/

    private String mLastSearchWord = "";

    /*public void searchBykeyword(String searchStr) {
        ZyUtils.getInstance().insertLog("searchBykeyword", "searchStr = " + searchStr);
        if (mLastSearchWord.equals(searchStr)) {
            return;
        }
        mLastSearchWord = searchStr;
        mCurPageIndex = OverallData.DEFAULT_REQ_PAGE_NUM;
        requestIndoorMendListData();
    }

    *//**
     * 获取户内整改记录列表
     *//*
    private void requestIndoorMendListData() {
        *//*LoginUserInfo loginUserInfo = BaseApplication.getLoginUserInfo();
        if (null == loginUserInfo || !ZyUtils.getInstance().isNetConnected()) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
            return;
        }*//*
        mIsReqListData = true;
        RequestParams httpParams = new RequestParams();
        httpParams.put("pageNum", mCurPageIndex);
        httpParams.put("pageSize", OverallData.REQ_PAGE_CNT);
        if (!TextUtils.isEmpty(mLastSearchWord)) {
            //searchValue
            httpParams.put("searchValue", mLastSearchWord);
        }
        if (null != mStatus && !"".equals(mStatus)) {
            httpParams.put("status", mStatus);
        } else {
            //请求全部
        }
        ZyUtils.getInstance().insertLog("requestIndoorMendListData", "req mCurPageIndex = "
                + mCurPageIndex + ", httpParams = " + ObjectUtil.objectToString(httpParams));
        Log.d("lhm", "req mCurPageIndex = " + mCurPageIndex + ", httpParams = " + ObjectUtil.objectToString(httpParams));
        AsyncHttpUtils.getInstance().get(SERVICE_DOMAIN + "/appApi/getIndoorMendList", httpParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                ZyUtils.getInstance().insertLog("requestIndoorMendListData", "onFailure statusCode = " +
                        statusCode + ", errorResponse = "+ responseString
                        + ", throwable = " + throwable.getMessage());
                ToastUtils.showRoundRectToast("获取列表数据失败：" + throwable.getMessage());
                *//*if (mCurPageIndex == OverallData.DEFAULT_REQ_PAGE_NUM) {
                    refreshLayout.finishRefresh();
                } else {
                    refreshLayout.finishLoadMore();
                }*//*
                mIsReqListData = false;
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("lhm", "requestIndoorMendListData responseString = " + responseString);
                IndoorMendListResp indoorMendListResp = BusinessHttpReqUtils.getInstance().parseJsonObj
                        (responseString, IndoorMendListResp.class);
                if (null != indoorMendListResp) {
                    if (indoorMendListResp.code == 200) {
                        int curPageDataCnt = null == indoorMendListResp.rows ? 0 : indoorMendListResp.rows.size();
                        if (mCurPageIndex == OverallData.DEFAULT_REQ_PAGE_NUM) {
                            mHomeAdapter.setList(curPageDataCnt == 0 ? new ArrayList<>() : indoorMendListResp.rows);
                            mCurListCnt = curPageDataCnt;
                            if (mCurListCnt == 0 || mCurListCnt >= indoorMendListResp.total) {
                                refreshLayout.finishRefreshWithNoMoreData();
                                if (mCurListCnt == 0 ) {
                                    showEmptyView();
                                }
                            } else {
                                refreshLayout.finishRefresh();
                                ++mCurPageIndex;
                            }
                        } else {
                            if (curPageDataCnt > 0 ) {
                                mHomeAdapter.addData(indoorMendListResp.rows);
                            }
                            mCurListCnt += curPageDataCnt;
                            if (curPageDataCnt == 0 || mCurListCnt >= indoorMendListResp.total) {
                                refreshLayout.finishLoadMoreWithNoMoreData();
                                ZyUtils.getInstance().insertLog("requestIndoorMendListData","没有更多数据");
                            } else {
                                refreshLayout.finishLoadMore();
                                ++mCurPageIndex;
                                ZyUtils.getInstance().insertLog("requestIndoorMendListData","有更多数据");
                            }
                        }
                    } else if (indoorMendListResp.code == 401){
                        //登陆失效，需重新登陆
                        BusinessHttpReqUtils.getInstance().autoPwdLogin(mContext);
                    } else {
                        ToastUtils.showRoundRectToast("获取列表数据失败: " + indoorMendListResp.msg);
                    }
                } else {
                    ToastUtils.showRoundRectToast("获取列表数据失败");
                }
                mIsReqListData = false;
            }
        });
    }*/

    @Override
    protected void initData() {

    }

    private TextView mWelcomeTv;
    /**
     * 顶部信息：地区、电话、banner、模块产品
     */
    private void initHeadView() {
        if (null != mStatus) {
            //户内整改记录列表页
            return;
        }
        //首页
        View headerView = LayoutInflater.from(mContext).inflate(R.layout.layout_home_header_view,
                null, false);
        if (null != headerView) {
            LoginUserInfo loginUserInfo = BaseApplication.getLoginUserInfo();
            mWelcomeTv = headerView.findViewById(R.id.welcome_tv);
            mWelcomeTv.setText(null != loginUserInfo ? "Hi~ " + loginUserInfo.nickName : "Hi");
            View phoneInfoView = headerView.findViewById(R.id.phone_info_ll);
            TextView phoneInfoTv = headerView.findViewById(R.id.phone_tv);
            phoneInfoTv.setText(OverallData.CUSTOMER_SERVICE_PHONE);
            phoneInfoView.setOnClickListener(v -> {
                //打电话
                Utils.callPhone(mContext, OverallData.CUSTOMER_SERVICE_PHONE);
            });
            Banner banner = headerView.findViewById(R.id.banner);
//            List<String> urlList = new ArrayList<>();//服务器banner
//            banner.setImages(urlList);
            ArrayList<Integer> localImgPathList = new ArrayList<>();
            localImgPathList.add(R.mipmap.banner);
            banner.setImages(localImgPathList);
            banner.setImageLoader(new GlideImageLoader());
            //设置指示器的位置，小点点，左中右。
            banner.setIndicatorGravity(BannerConfig.CENTER)
                    //以上内容都可写成链式布局，这是轮播图的监听。比较重要。方法在下面。
                    .setOnBannerListener(position -> {
                        //广告点击
//                        ToastUtils.showRoundRectToast("广告点击 todo");
                    })
                    //必须最后调用的方法，启动轮播图。
                    .start();
            headerView.findViewById(R.id.module_wei_xiu_ll).setOnClickListener(v -> {
                //维修模块点击,暂时不处理
                startActivity(new Intent(mContext, CreateMaintainOrderActivity.class));
                //ToastUtils.showRoundRectToast(StringUtil.getResString(R.string.to_do_prompt));
            });
            headerView.findViewById(R.id.module_xun_jian_ll).setOnClickListener(v -> {
                //巡检模块点击点击跳转【3030户外巡检】列表
                if (BaseApplication.isValidLogin((BaseActivity)getActivity(), true)) {
                    toActivity(new Intent(mContext, OutdoorSecurityCheckActivity.class));
                }
            });

            productFragment = new ProductFragment(0);
            mountingsFragment = new MountingsFragment(1);
            scLogFragment = new SCLogFragment("");
            mFragmentList.add(productFragment);
            mFragmentList.add(mountingsFragment);
            mFragmentList.add(scLogFragment);
            //init tab  radiogroup
            mTabRg = headerView.findViewById(R.id.tab_rg);
            //init viewpager
            mPager = headerView.findViewById(R.id.view_pager_2);
            mPager.setOffscreenPageLimit(2);
            mTabRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    if (checkedId == R.id.tab_product_rb) {
                        mPager.setCurrentItem(0, true);
                        Toast.makeText(mContext, "当前fragment 0", Toast.LENGTH_SHORT).show();
                    } else if (checkedId == R.id.tab_mountings_rb) {
                        mPager.setCurrentItem(1, true);
                        Toast.makeText(mContext, "当前fragment 1", Toast.LENGTH_SHORT).show();
                    } else if (checkedId == R.id.tab_sc_log_rb) {
                        mPager.setCurrentItem(2, true);
                        Toast.makeText(mContext, "当前fragment 2", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        /*mTabRg.setOnCheckedChangeListener((group, checkedId) -> {

        });*/

            mPager.setAdapter(new FragmentTabAdapter(getChildFragmentManager(), mFragmentList));
            mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    RadioButton radioButton = (RadioButton) mTabRg.getChildAt(position);
                    radioButton.setChecked(true);
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
            mHomeAdapter.addHeaderView(headerView);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginStateChange(LoginUserInfo event) {
        if (null == event) {
            return;
        }
        mWelcomeTv.setText( "Hi~ " + (event.isLogin && !TextUtils.isEmpty(event.userName) ? event.userName : ""));
        mCurPageIndex = OverallData.DEFAULT_REQ_PAGE_NUM;
        //requestIndoorMendListData();
    }
}
